<template>
  <NavBar title="购买资源包" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="purchase-resource-container">
    <!-- SVIP推广横幅 -->
    <view class="svip-banner">
      <view class="banner-content">
      <image class="svip-img" src="/static/svip.png" mode=""></image>
    
      </view>
    </view>
    <view class="svip-setion">
    <!-- 资源包选择区域 -->
    <view class="resource-section">
      <view class="section-header">
        <text class="section-title">选择要购买的资源包</text>
        <view class="record-link" @tap="goToRecord">资源包记录
		<view class="arrow">
			 <uni-icons type="right" color="#8B8B8B" size="16" ></uni-icons>
		</view>
		</view>
      </view>
      
      <view class="resource-grid">
        <view
          v-for="(pack, index) in resourcePacks"
          :key="pack.id"
          class="resource-item"
          :class="{ active: selectedPack === index }"
          @tap="selectPack(index)"
        >
          <text class="pack-count">{{ pack.package_value }}<text class="pack-price">次</text>
		  </text>
          <text class="pack-price">{{ formatPrice(pack.package_price) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 温馨提示 -->
    <view class="tips-section">
      <text class="tips-title">温馨提示:</text>
      <view class="tips-list">
        <text class="tip-item" v-for="(tip, index) in packageTips" :key="index">{{ tip }}</text>
      </view>
    </view>
    
    <!-- 支付方式选择 -->
    <view class="payment-section">
      <text class="section-title">选择支付方式</text>
      <view class="payment-options">
        <view 
          v-for="(method, index) in paymentMethods" 
          :key="index"
          class="payment-item"
          :class="{ active: selectedPayment === index }"
          @tap="selectPayment(index)"
        >
          <view class="payment-left">
            <view class="payment-icon">
              <image class="payment-icon-img" :src="method.iconSrc" mode="aspectFit"></image>
            </view>
            <text class="payment-name">{{ method.name }}</text>
          </view>
          <view class="radio-button" :class="{ active: selectedPayment === index }">
            <text class="checkmark" v-if="selectedPayment === index">✓</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部支付栏 -->
    <view class="bottom-payment">
      <view class="payment-info">
        <text class="payment-label">需支付:</text>
        <text class="payment-amount">{{ selectedPackPrice }}</text>
      </view>
      <view class="payment-right" @tap="handlePayment">支付</view>
    </view>

	</view>

    <!-- 登录弹窗组件 -->
    <LoginModal
      ref="loginModalRef"
      @close="onLoginModalClose"
      @skip="onLoginSkip"
      @login="onLoginSuccess"
    />

    <!-- 支付成功弹窗 -->
    <CommonPopup
      ref="successPopup"
      :title="popupTitle"
      :message="popupMessage"
      :type="popupType"
    />
  </view>
  </NavBar>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { PACKAGE_API } from '../../config/api.js'
import { isLoggedIn, getToken, getCurrentUser, fetchUserInfo, navigateToLogin } from '../../utils/user.js'
import { isWeixinMiniProgram } from '../../utils/platform.js'
import { getRuleConfig } from '../../utils/config.js'
import LoginModal from '@/components/LoginModal/LoginModal.vue'
import CommonPopup from '@/components/CommonPopup/CommonPopup.vue'

// 响应式数据
const selectedPack = ref(0)
const selectedPayment = ref(0) // 默认选择第一个可用支付方式
const loading = ref(false)
const loginModalRef = ref()
const successPopup = ref(null)

// 弹窗控制数据
const popupTitle = ref('购买成功')
const popupMessage = ref('购买成功')
const popupType = ref('success')

// 资源包选项 - 从API获取
const resourcePacks = ref([])

// 温馨提示
const packageTips = ref([
  '1. 充值只可选择以上固定档位金额。',
  '2. 充值次数只能在小程序中使用。',
  '3. 充值次数永久有效。'
])

// 所有支付方式
const allPaymentMethods = [
  {
    name: '金豆',
    icon: '',
    iconClass: 'gold-beans',
    type: 3,
    iconSrc: '/static/svip9.png'
  },
  {
    name: '支付宝',
    icon: '',
    iconClass: 'alipay',
    type: 2,
    iconSrc: '/static/svip8.png'
  },
  {
    name: '微信',
    icon: '',
    iconClass: 'wechat',
    type: 1,
    iconSrc: '/static/svip10.png'
  }
]

// 判断当前平台
const isWeixinMP = ref(isWeixinMiniProgram())

// 计算可用的支付方式
const paymentMethods = computed(() => {
  const methods = []

  // 金豆始终排在第一个
  methods.push(allPaymentMethods[0]) // 金豆

  if (isWeixinMP.value) {
    // 微信小程序：显示微信支付，隐藏支付宝
    methods.push(allPaymentMethods[2]) // 微信
  } else {
    // 非微信小程序：显示支付宝支付，隐藏微信
    methods.push(allPaymentMethods[1]) // 支付宝
  }

  return methods
})

// 格式化价格显示
const formatPrice = (price) => {
  const selectedMethod = paymentMethods.value[selectedPayment.value]
  if (selectedMethod.name === '金豆') {
    return `${price}金豆`
  } else {
    // 微信和支付宝支付需要将price从分换算成元
    const priceInYuan = (price / 100).toFixed(2)
    return `¥${priceInYuan}`
  }
}

// 计算属性 - 选中资源包的价格
const selectedPackPrice = computed(() => {
  if (resourcePacks.value.length === 0) return '0元'
  const selectedPackData = resourcePacks.value[selectedPack.value]
  return formatPrice(selectedPackData.package_price)
})

// 获取资源包列表
const fetchResourcePacks = async () => {
  try {
    loading.value = true

    const response = await uni.request({
      url: `${PACKAGE_API.LIST}?page=1&page_size=10`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    })

    console.log('资源包列表API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      resourcePacks.value = response.data.data.list || []
      console.log('资源包列表加载成功:', resourcePacks.value)
    } else {
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '获取资源包列表失败'
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }
  } catch (error) {
    console.error('获取资源包列表失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  } finally {
    loading.value = false
  }
}

// 方法
const goBack = () => {
  uni.navigateBack()
}

const selectPack = (index) => {
  selectedPack.value = index
}

const selectPayment = (index) => {
  selectedPayment.value = index
}

const goToRecord = () => {
  uni.navigateTo({
    url: '/pages/resource-record/resource-record'
  })
}

// 登录弹窗相关方法
const showLoginModal = () => {
  loginModalRef.value?.open()
}

const onLoginModalClose = () => {
  console.log('登录弹窗关闭')
}

const onLoginSkip = () => {
  uni.showToast({
    title: '暂不登录',
    icon: 'none',
    duration: 2000
  })
}

const onLoginSuccess = () => {
  // 弹框处理了登录逻辑 这里只处理登录完成逻辑
  console.log('登录成功，可以继续支付流程')
}

const handlePayment = async () => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    // 判断是否为微信小程序
    if (isWeixinMiniProgram()) {
      // 微信小程序显示登录弹窗
      showLoginModal()
    } else {
      // 其他平台跳转到登录页面
      navigateToLogin('/pages/purchase-resource/purchase-resource')
    }
    return
  }

  if (resourcePacks.value.length === 0) {
    uni.showToast({
      title: '请选择资源包',
      icon: 'none',
      duration: 2000
    })
    return
  }

  const selectedPackData = resourcePacks.value[selectedPack.value]
  const selectedPaymentData = paymentMethods.value[selectedPayment.value]

  // 如果是金豆支付，需要先判断用户金豆余额
  if (selectedPaymentData.type === 3) {
    const user = getCurrentUser()
    const userBeans = user?.bean || 0
    const packagePrice = selectedPackData.package_price

    if (userBeans < packagePrice) {
      uni.showToast({
        title: '金豆不足，无法支付',
        icon: 'none',
        duration: 2000
      })
      return
    }
  }

  try {
    uni.showLoading({
      title: '创建支付订单...'
    })

    const token = getToken()
    const requestData = {
      package_id: selectedPackData.id,
      pay_type: selectedPaymentData.type
    }

    const response = await uni.request({
      url: PACKAGE_API.PURCHASE,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: requestData
    })

    console.log('资源包购买API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      uni.hideLoading()

      // 根据支付方式处理不同的响应
      if (selectedPaymentData.type === 1) {
        // 微信支付需要调起支付
        const paymentData = response.data.data
        await callWechatPay(paymentData.pay_data)
      } else if (selectedPaymentData.type === 2) {
        // 支付宝支付需要调起支付
        const paymentParams = response.data.data
        await callAlipay(paymentParams)
      } else if (selectedPaymentData.type === 3) {
        // 金豆支付已经完成扣费，直接处理成功
        await handlePaymentSuccess()
      }
    } else {
      uni.hideLoading()
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '创建支付订单失败'
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('支付失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  }
}

// 调起微信支付
const callWechatPay = async (payData) => {
  try {
    console.log('微信支付参数:', payData)

    // #ifdef MP-WEIXIN
    await wx.requestPayment({
      timeStamp: payData.timestamp,
      nonceStr: payData.noncestr,
      package: payData.package,
      signType: 'RSA',
      paySign: payData.sign
    })

    console.log('微信支付成功')
    await handlePaymentSuccess()
  } catch (error) {
    if (error.errMsg === 'requestPayment:fail cancel') {
      uni.showToast({
        title: '支付已取消',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: '支付失败',
        icon: 'error'
      })
    }
  }
}

// 调起支付宝支付
const callAlipay = async (paymentParams) => {
  try {
    console.log('支付宝支付参数:', paymentParams)

    // 检查是否有支付宝支付数据
    if (!paymentParams || !paymentParams.pay_data || !paymentParams.pay_data.order_string) {
      throw new Error('支付参数不完整')
    }

    // 使用uni.requestPayment调起支付宝支付
    await uni.requestPayment({
      provider: 'alipay',
      orderInfo: paymentParams.pay_data.order_string,
      success: (res) => {
        console.log('支付宝支付成功:', res)
      },
      fail: (err) => {
        console.error('支付宝支付失败:', err)
        throw err
      }
    })

    console.log('支付宝支付成功')
    await handlePaymentSuccess()

  } catch (error) {
    console.error('支付宝支付错误:', error)

    // 处理不同的错误情况
    if (error.errMsg) {
      if (error.errMsg.includes('cancel')) {
        uni.showToast({
          title: '支付已取消',
          icon: 'none'
        })
      } else if (error.errMsg.includes('fail')) {
        uni.showToast({
          title: '支付失败',
          icon: 'error'
        })
      } else {
        uni.showToast({
          title: error.errMsg || '支付失败',
          icon: 'error'
        })
      }
    } else {
      uni.showToast({
        title: error.message || '支付失败',
        icon: 'error'
      })
    }
  }
}

// 支付成功后的处理
const handlePaymentSuccess = async () => {
  // 刷新用户信息
  try {
    await fetchUserInfo()
    console.log('用户信息刷新成功')
  } catch (error) {
    console.error('刷新用户信息失败:', error)
  }

  // 获取当前选择的资源包信息
  const selectedPackData = resourcePacks.value[selectedPack.value]

  // 设置弹窗内容
  popupTitle.value = '购买成功'
  popupMessage.value = `获得${selectedPackData.package_value}次拍照搜题次数。`
  popupType.value = 'success'

  // 显示弹窗
  successPopup.value.show()
}

// 加载温馨提示
const loadPackageTips = async () => {
  try {
    const ruleConfig = await getRuleConfig(false)
    console.log('资源包温馨提示配置:', ruleConfig)

    // 读取 package_rule 字段
    if (ruleConfig.package_rule) {
      // 根据 \n 分割规则
      const tips = ruleConfig.package_rule.split('\n').filter(tip => tip.trim() !== '')
      if (tips.length > 0) {
        packageTips.value = tips
        console.log('资源包温馨提示加载成功:', tips)
      } else {
        console.log('没有配置资源包温馨提示，使用默认提示')
      }
    } else {
      console.log('没有配置 package_rule 字段，使用默认提示')
    }
  } catch (error) {
    console.error('加载资源包温馨提示失败:', error)
    // 使用默认提示
  }
}

// 页面加载时初始化
onMounted(() => {
  console.log('购买资源包页面加载')
   
  fetchResourcePacks()
  loadPackageTips()
})
</script>

<style scoped>
.purchase-resource-container {
  min-height: 100vh;
  position: relative;
  background-color: #fff;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 10rpx;
  background: transparent;
}

.status-time {
  font-size: 34rpx;
  font-weight: 600;
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.status-icon {
  font-size: 24rpx;
  color: #000;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.3);
}

.back-icon {
  font-size: 32rpx;
  color: white;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 700;
  color: white;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.nav-placeholder {
  width: 60rpx;
  height: 60rpx;
  background: white;
  border-radius: 8rpx;
}

/* SVIP推广横幅 */
.svip-banner {
  height: 442rpx;
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.banner-left {
  flex: 1;
}

.svip-title {
  font-size: 40rpx;
  font-weight: 800;
  color: white;
  display: block;
  margin-bottom: 12rpx;
}

.svip-desc {
  font-size: 24rpx;
  color: white;
  opacity: 0.9;
  line-height: 1.4;
}

.banner-right {
  position: relative;
}

.vip-box {
  position: relative;
  width: 120rpx;
  height: 80rpx;
  background: rgba(33, 150, 243, 0.3);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.vip-content {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.gold-coin {
  width: 40rpx;
  height: 40rpx;
  background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 8rpx rgba(255, 215, 0, 0.3);
}
.svip-setion{
	background: #fff;
	height: 80%;
	margin-top: -50rpx;
	position: absolute;
	top:430rpx ;
	left: 0;
	width: 100%;
	z-index: 55;
	border-radius: 20rpx;
}
.coin-text {
  font-size: 20rpx;
  font-weight: bold;
  color: white;
}

.v-shapes {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}
.svip-img{
	width: 100%;
	height: 442rpx;
}
.v-shape {
  font-size: 12rpx;
  color: rgba(255, 255, 255, 0.6);
  font-weight: bold;
}

.vip-text {
  position: absolute;
  right: -30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16rpx;
  font-weight: bold;
  color: white;
  writing-mode: vertical-rl;
}

/* 资源包选择区域 */
.resource-section {
  background: white;
  padding: 30rpx;
}
.payment-right{
	height: 92rpx;
	width: 50%;
	background-color: #565FFD;
	border-radius: 0 30rpx 30rpx 0;
	color: #fff;
	line-height: 92rpx;
	text-align: center;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.record-link {
  font-size: 24rpx;
  color: #666;
  display: flex;
  align-items: center;
}

.resource-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.resource-item {
  background: #ECF5FF;
  border: 2rpx solid #E9ECEF;
  padding: 12rpx 16rpx;
  text-align: center;
  transition: all 0.3s ease;
  border-radius: 16rpx;
  height: 132rpx;
  box-sizing: border-box;
}

.resource-item.active {
  border-color: #2196F3;
  background: #F0F7FF;
  border:5rpx solid #565FFD;
  background: linear-gradient(180deg, #fff 0%, #C4DEFF 100%);
}

.pack-count {
  font-size: 40rpx;
  font-weight: 600;
  color: #333;
  display: block;
}

.pack-price {
  font-size: 28rpx;
  color: #999;
}

/* 温馨提示 */
.tips-section {
  background: white;
  padding: 30rpx;
}

.tips-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.tips-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.tip-item {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

/* 支付方式选择 */
.payment-section {
  background: white;
  padding: 30rpx 30rpx 20rpx;
}

.payment-options {
  margin-top: 20rpx;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx ;
  box-sizing: border-box;
  border: 1rpx solid #E5E5E5;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
}



.payment-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.payment-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-icon {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-icon-img {
  width: 48rpx;
  height: 48rpx;
}

.icon-text {
  font-size: 24rpx;
  color: white;
  font-weight: bold;
}

.payment-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.radio-button {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #D9D9D9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.radio-button.active {
  border-color: #565FFD;
  background: #565FFD;
}

.checkmark {
  font-size: 20rpx;
  color: white;
  font-weight: bold;
}

/* 底部支付栏 */
.bottom-payment {

  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 66;
  border-radius: 80rpx;
  width: 92%;
  height: 92rpx;
  margin: 0 auto;
}

.payment-info {
	width: 50%;
  display: flex;
  align-items: center;
  gap: 8rpx;
  background-color: #E0DCDC;
 height: 92rpx;
 border-radius: 30rpx 0 0 30rpx;
 padding-left: 20rpx;
 color: #8B8B8B;
 text-align: center;
 justify-content: center;
}

.payment-label {
  font-size: 28rpx;
  color: #666;
}

.payment-amount {
  font-size: 32rpx;
  font-weight: 600;
}

.pay-button {
  color: white;
  font-size: 32rpx;
  font-weight: 600;
  padding: 24rpx 60rpx;
  border-radius: 44rpx;
  border: none;
  transition: all 0.3s ease;
  height: 90rpx;
  background-color: #565FFD;
}


/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .resource-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .resource-item {
    padding: 20rpx 12rpx;
  }
}

/* 安全区域适配 */
@supports (padding: max(0px)) {
  .bottom-payment {
    padding-bottom: max(20rpx, env(safe-area-inset-bottom));
  }
}
</style>
